package com.origin.uilibrary

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import com.origin.utils.log.LogUtils
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.callbackFlow


// 构建输入框文字变化流
fun EditText.textChangeFlow(): Flow<String> = callbackFlow {
    // 构建输入框监听器
    val watcher = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {}
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        // 在文本变化后向流发射数据
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            s?.let { offer(it.toString()) }
        }
    }
    addTextChangedListener(watcher) // 设置输入框监听器
    awaitClose { removeTextChangedListener(watcher) } // 阻塞以保证流一直运行
}

// 防抖点击
fun View.clickFlow() = callbackFlow {
    setOnClickListener { offer(Unit) }
    awaitClose { setOnClickListener(null) }
}



private var debounceJob: Job? = null

fun debounce(
    delayMs: Long = 200,
    parentScope: CoroutineScope = CoroutineScope(Dispatchers.Main),
    action: suspend CoroutineScope.() -> Unit
) {
    debounceJob?.cancel()
    debounceJob = parentScope.launch {
        delay(delayMs)
        action()
    }
}

fun View.setDebounceClickListener(listener: View.OnClickListener, time: Long = 300L) {
    var job: CoroutineScope? = null
    this.setOnClickListener {
        if (job != null) {
            return@setOnClickListener
        }
        job = CoroutineScope(Dispatchers.Main)

        job?.launch {
            listener.onClick(it)
            delay(time)
            job?.cancel()
            job = null
        }
    }
}


/**
 * 添加点击缩放效果
 */

// 参数为：缩小比例、缩小的变化时间
@SuppressLint("ClickableViewAccessibility")
fun View.addClickScale(scale: Float = 0.9f, duration: Long = 150) {
    this.setOnTouchListener { _, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                this.animate().scaleX(scale).scaleY(scale).setDuration(duration).start()
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                this.animate().scaleX(1f).scaleY(1f).setDuration(duration).start()
            }
        }
        this.onTouchEvent(event)
    }
}


// 下面的别删除

//private val _etState = MutableStateFlow("")
//
//GlobalScope.launch(Dispatchers.Main) {
//    _etState.debounce(1000).collect  {
//        search(it)
//    }
//}
//
//_etState.value = this
